#!/bin/bash

# 定义版本号
DOCKER_VERSION=24.0.7
DOCKER_COMPOSE_VERSION=v2.2.3
TAG="7.3.6"
BASE_DIR=$(dirname $0)/..

# 判断是不是 root 用户，非 root 用户无法执行安装
if [ $USER != "root" ]
then
    echo "ERROR: Unable to perform installation as non-root user."
    exit
fi

echo "当前目录......"
echo $BASE_DIR


# 查找空间最大目录
df_lines=$(df -P | wc -l)
max_dir=''
max_siz=0
for i in $(seq 2 $df_lines)
do
    temp_siz=$(df -P | awk -v i=$i 'NR==i{print $4}')
    if [ $temp_siz -gt $max_siz ];then
        max_siz=$temp_siz
        max_dir=$(df -P | awk -v i=$i 'NR==i{print $NF}')
    fi
done
echo "当前磁盘最大目录......"
echo $max_dir

echo "定义docker目录......"
mkdir -p $max_dir/docker
mkdir -p $max_dir/docker/tmp




#linux 7的防火墙关闭操作
firewalld(){
  systemctl status firewalld | grep "running" &>/dev/null
  if [ $? -eq 0 ]
  then
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙处于开启状态,需要进行关闭操作！"
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙正在关闭中..."
    systemctl stop firewalld &>/dev/null
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙已经关闭！"
    #再次检查防火墙状态
    systemctl status firewalld | grep "running" &>/dev/null
    if [ $? -ne 0 ]
    then
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙已经处于关闭状态,关闭操作成功"
    else
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙已经处于开启状态,关闭操作失败，请手台操作！"
    fi
  else
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙已经处于关闭状态,无需进行关闭操作"
  fi
}
#linux 6的防火墙关闭操作
iptable(){
  service iptables status | grep "is not running" &>/dev/null
  if [ $? -eq 0 ]
  then
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙处于关闭状态,无需要进行关闭操作！"
  else
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙处于开启状态,需要进行关闭操作！"
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙正在关闭中..."
    service iptables stop
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙已经关闭！"
    #再次判断防火墙的状态
    service iptables status | grep "is not running" &>/dev/null
    if [ $? -ne ]
    then
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙处于开启状态,进行关闭操作失败，请后台操作！"
    else
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 防火墙处于关闭状态,关闭操作成功！"
    fi
  fi
}
#防护检查函数
selinux(){
  #判断当前的状态
  result=`getenforce`
  if [ $result = Enforing ]
  then
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` selinux是开启状态，需要关闭！"
    #临时关闭操作
    setenforce 0 &>/dev/null
    #永久关闭操作
    find_key="SELINUX="
    sed -ri "/^$find_key/c${find_key}disabled" /etc/selinux/config
    result_1=`getenforce`
    if [ $result_1 = Enforing ]
    then
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` selinux关闭操作失败，请手台进行操作"
      exit 2
    else
      echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` selinux关闭成功继续部署"
    fi
  else
    echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` selinux是关闭状态，无需操作！"
  fi
}

function getIpAddr(){
	# 获取IP命令
	ipaddr=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
	array=(`echo $ipaddr | tr '\n' ' '` ) 	# IP地址分割，区分是否多网卡
	#array=(172.20.32.214 192.168.1.10);
	num=${#array[@]}  						#获取数组元素的个数

	# 选择安装的IP地址
	if [ $num -eq 1 ]; then
		#echo "*单网卡"
		local_ip=${array[*]}
	elif [ $num -gt 1 ];then
	  echo -e "\033[035m******************************\033[0m"
		echo -e "\033[036m*    请选择安装的IP地址		\033[0m"
		i=1
	  for var in "${array[@]}";
      do
          echo -e "\033[032m*      $i : $var 		\033[0m"
          ((i++))
      done
		echo -e "\033[035m******************************\033[0m"
		#选择需要安装的服务类型
		input=1
		while :
		do
			read -r -p "*请选择安装的IP地址(序号): " input
			if [[ $input -ge  1 && $input -lt  $i ]]; then
        index=$[input -1]
        local_ip=${array[index]}
        break
      else
	      echo "*请输入有效的数字:"
			  exit 1
      fi
		done
	else
		echo -e "\033[31m*未设置网卡IP，请检查服务器环境！ \033[0m"
		exit 1
	fi
}



# 校验IP地址合法性
function isValidIp() {
	local ip=$1
	local ret=1

	if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
		ip=(${ip//\./ }) # 按.分割，转成数组，方便下面的判断
		[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
		ret=$?
	fi
	return $ret
}


#服务器的操作系统的判断
edition=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
ed=`cat /etc/redhat-release`
if [ "X$edition" == "X6"  ]
then
	echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 当前服务器操作系统版本是linux 6版本系统，具体版本：$ed "
	iptable
	selinux
elif [ "X$edition" == "X7"  ]
then
	echo -e "INFO `date +%Y-%m-%d_%H:%M:%S` 当前服务器操作系统版本是linux 7版本系统，具体版本：$ed "
	firewalld
	selinux
fi


echo "配置目录权限......"
chown -R 5000:5000 conf logs nacos  seata data wait-for-it.sh
chmod -R 777 *
chmod 644 mysql/conf/my.cnf

# 生成 daemon.json 配置文件
echo "进行docker配置......"
mkdir -p /etc/docker/
cat > /etc/docker/daemon.json << EOF
{
    "data-root": "$max_dir/docker",
    "registry-mirrors": ["http://dev.redxun.cn:20080","https://ia6yk7d7.mirror.aliyuncs.com"],
    "insecure-registries":["dev.redxun.cn:20080"]
}
EOF

# 获取主机网卡IP地址
echo "获取主机网卡IP地址并写入环境变量......"

local_ip=$(cat .env |grep -o "HOST_IP=.*"| awk -F"=" '{print $2}')

if [[ -z $local_ip ]];   then
  getIpAddr	#自动获取IP
  isValidIp ${local_ip}	# IP校验
  if [ $? -ne 0 ]; then
    echo -e "\033[31m*自动获取的IP地址无效，请重试！ \033[0m"
    exit 1
  fi
fi


#ipAddr=$(ip addr show | grep inet | grep -v inet6 | grep '/24' | awk '{print $2}' | awk -F '/' '{print $1}')
#echo "网卡IP地址：$ipAddr"
echo "*选择安装的IP地址为：${local_ip}"

cat > .env << EOF
REGISTER=
TAG=$TAG
HOST_IP=${local_ip}
MYSQL_PW=Redxun2022Mysql
NACOS_PW=Redxun2022Nacos
REDIS_PW=Redxun2022redis
REGISTRY_URL=dev.redxun.cn:20080/jpaas$TAG
EOF

echo "检查docker环境......"
docker -v
if [[ $? -eq 0 ]]; then
  echo "检查到docker已经安装! 跳过安装步骤"
else
  # 安装 docker
  # curl -O https://download.docker.com/linux/static/stable/$(uname -m)/docker-${DOCKER_VERSION}.tgz
  tar -zxvf docker-${DOCKER_VERSION}.tgz
  chmod +x docker/*
  mv docker/* /usr/bin
  dockerd --version

  # 检查 docker 是否安装成功
  if [ $? -ne 0 ]
  then
      echo "ERROR: docker install failed."
      rm -rf docker docker-${DOCKER_VERSION}.tgz
      exit
  fi
  # rm -rf docker docker-${DOCKER_VERSION}.tgz

  # 启动 dockerd
  nohup dockerd > /var/log/dockerd.log 2>&1 &

  # 检查 dockerd 是否启动成功
  pidof dockerd
  if [ $? -ne 0 ]
  then
      echo "ERROR: dockerd failed to start."
      exit
  fi

  # 设置 dockerd 开机自启动
  echo "nohup dockerd > /var/log/dockerd.log 2>&1 &" >> /etc/rc.local
  chmod +x /etc/rc.local

fi

if which docker-compose >/dev/null; then
 echo "检测到 Docker Compose 已安装，跳过安装步骤"
 docker-compose -v
else
  # 安装 docker-compose
  #curl -L "https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose 2>&1 | tee -a ${CURRENT_DIR}/install.log
  cp docker-compose-linux-x86_64 /usr/local/bin/docker-compose
  chmod +x /usr/local/bin/docker-compose
  ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
 docker-compose -version
 echo "... 在线安装 docker-compose 成功"

  # 检查 docker compose 是否安装成功
  if [ $? -ne 0 ]
  then
      echo "ERROR: docker compose install failed."
      exit
  fi
fi

echo "转换linux文件格式......"
#find . -type f -print0 | xargs -0 sed -i "s/\r//g"
sed -i 's/\r//' wait-for-it.sh
sed -i 's/\r//' build.sh
sed -i 's/\r//' tag.sh
sed -i 's/\r//' push.sh
cd nacos/bin
sed -i 's/\r//' docker-startup.sh
cd ..
cd ..
cd seata/bin
sed -i 's/\r//' seata-start.sh
cd ..
cd ..

echo "当前TAG......"
echo $TAG


echo "构建后的docker images镜像列表:"
docker images

echo "当前正在运行的Docker容器实例列表:"
docker ps

